<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据筛选与分析工具</title>
    <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 15px;
        }
        .upload-section {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
            border: 1px dashed #ced4da;
        }
        .upload-section h2 {
            margin-bottom: 15px;
            color: #495057;
        }
        .file-input-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 15px;
        }
        .file-input-item {
            flex: 1;
            min-width: 200px;
        }
        .file-input-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #495057;
        }
        .file-input-item input[type="file"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }
        .file-input-container button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            height: fit-content;
            align-self: flex-end;
        }
        .file-input-container button:hover {
            background-color: #2980b9;
        }
        .filter-section {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
        }
        .filter-section h2 {
            margin-bottom: 15px;
            color: #495057;
        }
        .data-type-selector {
            margin-bottom: 20px;
        }
        .data-type-selector select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 16px;
        }
        .filter-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .filter-option {
            display: flex;
            flex-direction: column;
        }
        .filter-option label {
            margin-bottom: 5px;
            font-weight: bold;
            color: #495057;
        }
        .filter-option input {
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }
        .action-buttons {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        .action-buttons button {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            min-width: 150px;
        }
        #filterBtn {
            background-color: #2ecc71;
            color: white;
        }
        #filterBtn:hover {
            background-color: #27ae60;
        }
        #exportExcelBtn {
            background-color: #e74c3c;
            color: white;
        }
        #exportExcelBtn:hover {
            background-color: #c0392b;
        }
        #exportTencentBtn {
            background-color: #9b59b6;
            color: white;
        }
        #exportTencentBtn:hover {
            background-color: #8e44ad;
        }
        .action-buttons button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        .results-section {
            overflow-x: auto;
        }
        .results-section h2 {
            margin-bottom: 15px;
            color: #495057;
        }
        .result-category {
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
        }
        .result-category h3 {
            background-color: #3498db;
            color: white;
            padding: 12px 15px;
            margin: 0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }
        th {
            background-color: #f8f9fa;
            color: #495057;
            position: sticky;
            top: 0;
        }
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        tr:hover {
            background-color: #e9f7fe;
        }
        .no-data {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }
        .file-status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            font-weight: bold;
        }
        .file-status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .file-status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .tencent-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .tencent-modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            max-width: 500px;
            width: 90%;
            text-align: center;
        }
        .tencent-modal h3 {
            margin-bottom: 15px;
            color: #2c3e50;
        }
        .tencent-modal p {
            margin-bottom: 20px;
            color: #7f8c8d;
        }
        .tencent-link {
            display: block;
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin: 15px 0;
            word-break: break-all;
            border: 1px solid #e9ecef;
        }
        .modal-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
        }
        .modal-buttons button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        #copyLinkBtn {
            background-color: #3498db;
            color: white;
        }
        #closeModalBtn {
            background-color: #95a5a6;
            color: white;
        }
        @media (max-width: 768px) {
            .filter-options {
                grid-template-columns: 1fr;
            }
            .action-buttons {
                flex-direction: column;
            }
            .file-input-container {
                flex-direction: column;
            }
            .modal-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>数据筛选与分析工具</h1>
        
        <div class="upload-section">
            <h2>上传数据文件</h2>
            <div class="file-input-container">
                <div class="file-input-item">
                    <label for="fileCurrent">本周基础数据</label>
                    <input type="file" id="fileCurrent" accept=".xlsx, .xls" data-type="current">
                </div>
                <div class="file-input-item">
                    <label for="fileHistory">历史基础数据</label>
                    <input type="file" id="fileHistory" accept=".xlsx, .xls" data-type="history">
                </div>
                <div class="file-input-item">
                    <label for="fileCurrentSupplies">本周辎重使用数据</label>
                    <input type="file" id="fileCurrentSupplies" accept=".xlsx, .xls" data-type="currentSupplies">
                </div>
                <div class="file-input-item">
                    <label for="fileTodaySupplies">今日辎重使用数据</label>
                    <input type="file" id="fileTodaySupplies" accept=".xlsx, .xls" data-type="todaySupplies">
                </div>
                <button id="uploadBtn">上传文件</button>
            </div>
            <div id="fileStatus" class="file-status"></div>
        </div>
        
        <div class="filter-section">
            <h2>筛选条件</h2>
            <div class="data-type-selector">
                <select id="dataType">
                    <option value="current">本周基础数据</option>
                    <option value="history">历史基础数据</option>
                    <option value="currentSupplies">本周辎重使用数据</option>
                    <option value="todaySupplies">今日辎重使用数据</option>
                </select>
            </div>
            
            <div class="filter-options" id="filterOptions">
                <!-- 筛选条件将根据选择的数据类型动态生成 -->
            </div>
            
            <div class="action-buttons">
                <button id="filterBtn">筛选数据</button>
                <button id="exportExcelBtn" disabled>导出为Excel</button>
                <button id="exportTencentBtn" disabled>导出到腾讯文档</button>
            </div>
        </div>
        
        <div class="results-section">
            <h2>筛选结果</h2>
            <div id="resultsContainer"></div>
        </div>
    </div>

    <!-- 腾讯文档导出模态框 -->
    <div class="tencent-modal" id="tencentModal">
        <div class="tencent-modal-content">
            <h3>腾讯文档链接已生成</h3>
            <p>请复制以下链接在浏览器中打开：</p>
            <div class="tencent-link" id="tencentLink">链接生成中...</div>
            <div class="modal-buttons">
                <button id="copyLinkBtn">复制链接</button>
                <button id="closeModalBtn">关闭</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentData = {};
        let currentDataType = null;
        let currentFilterResults = {}; // 存储当前的筛选结果
        let hasUploadedFiles = false; // 标记是否有文件上传成功
        
        // DOM元素
        const fileInputs = document.querySelectorAll('input[type="file"]');
        const uploadBtn = document.getElementById('uploadBtn');
        const fileStatus = document.getElementById('fileStatus');
        const dataType = document.getElementById('dataType');
        const filterOptions = document.getElementById('filterOptions');
        const filterBtn = document.getElementById('filterBtn');
        const exportExcelBtn = document.getElementById('exportExcelBtn');
        const exportTencentBtn = document.getElementById('exportTencentBtn');
        const resultsContainer = document.getElementById('resultsContainer');
        const tencentModal = document.getElementById('tencentModal');
        const tencentLink = document.getElementById('tencentLink');
        const copyLinkBtn = document.getElementById('copyLinkBtn');
        const closeModalBtn = document.getElementById('closeModalBtn');
        
        // 初始化筛选条件
        updateFilterOptions();
        
        // 事件监听
        uploadBtn.addEventListener('click', handleFileUpload);
        dataType.addEventListener('change', updateFilterOptions);
        filterBtn.addEventListener('click', filterData);
        exportExcelBtn.addEventListener('click', exportFilterResults);
        exportTencentBtn.addEventListener('click', exportToTencentDocs);
        copyLinkBtn.addEventListener('click', copyTencentLink);
        closeModalBtn.addEventListener('click', () => tencentModal.style.display = 'none');
        
        // 处理文件上传
        function handleFileUpload() {
            let uploadedCount = 0;
            let totalSelectedFiles = 0;
            
            // 计算实际选择的文件数量
            fileInputs.forEach(input => {
                if (input.files[0]) {
                    totalSelectedFiles++;
                }
            });
            
            if (totalSelectedFiles === 0) {
                showFileStatus('请至少选择一个文件', 'error');
                return;
            }
            
            // 重置上传状态
            hasUploadedFiles = false;
            showFileStatus('正在上传文件...', '');
            
            fileInputs.forEach(input => {
                const file = input.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                        
                        // 提取表头和数据
                        const headers = jsonData[0];
                        const rows = jsonData.slice(1);
                        
                        // 转换为对象数组
                        const processedData = rows.map(row => {
                            const obj = {};
                            headers.forEach((header, index) => {
                                let value = row[index];
                                
                                // 处理带"万"的数据
                                if (typeof value === 'string' && value.includes('万')) {
                                    value = convertWanToNumber(value);
                                }
                                
                                obj[header] = value;
                            });
                            return obj;
                        });
                        
                        // 根据文件类型存储数据
                        const fileType = input.getAttribute('data-type');
                        currentData[fileType] = processedData;
                        
                        uploadedCount++;
                        
                        if (uploadedCount === totalSelectedFiles) {
                            hasUploadedFiles = true;
                            showFileStatus(`成功上传 ${uploadedCount} 个文件`, 'success');
                            exportExcelBtn.disabled = false; // 启用导出按钮
                            exportTencentBtn.disabled = false; // 启用腾讯文档导出按钮
                        }
                    } catch (error) {
                        console.error('Error reading file:', error);
                        showFileStatus(`文件 ${file.name} 读取失败，请检查文件格式`, 'error');
                    }
                };
                reader.readAsArrayBuffer(file);
            });
        }
        
        // 将带"万"的数据转换为数字
        function convertWanToNumber(value) {
            if (typeof value !== 'string') return value;
            
            // 移除"万"字并转换为数字
            const numStr = value.replace('万', '');
            const num = parseFloat(numStr);
            
            // 如果是有效数字，乘以10000
            if (!isNaN(num)) {
                return num * 10000;
            }
            
            return value;
        }
        
        // 显示文件状态
        function showFileStatus(message, type) {
            fileStatus.textContent = message;
            fileStatus.className = type ? 'file-status ' + type : 'file-status';
        }
        
        // 更新筛选条件
        function updateFilterOptions() {
            currentDataType = dataType.value;
            let html = '';
            
            switch(currentDataType) {
                case 'current':
                    html = `
                        <div class="filter-option">
                            <label for="topWeekMilitary">周武勋前N名</label>
                            <input type="number" id="topWeekMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomWeekMilitary">周武勋后N名</label>
                            <input type="number" id="bottomWeekMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="topProsperity">繁荣度前N名</label>
                            <input type="number" id="topProsperity" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomProsperity">繁荣度后N名</label>
                            <input type="number" id="bottomProsperity" min="1" value="10">
                        </div>
                    `;
                    break;
                case 'history':
                    html = `
                        <div class="filter-option">
                            <label for="topHistoryMilitary">历史武勋前N名</label>
                            <input type="number" id="topHistoryMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomHistoryMilitary">历史武勋后N名</label>
                            <input type="number" id="bottomHistoryMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="topProsperity">繁荣度前N名</label>
                            <input type="number" id="topProsperity" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomProsperity">繁荣度后N名</label>
                            <input type="number" id="bottomProsperity" min="1" value="10">
                        </div>
                    `;
                    break;
                case 'currentSupplies':
                    html = `
                        <div class="filter-option">
                            <label for="topWeekMilitary">本周武勋前N名</label>
                            <input type="number" id="topWeekMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomWeekMilitary">本周武勋后N名</label>
                            <input type="number" id="bottomWeekMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="topSupplies">本周辎重使用前N名</label>
                            <input type="number" id="topSupplies" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomSupplies">本周辎重使用后N名</label>
                            <input type="number" id="bottomSupplies" min="1" value="10">
                        </div>
                    `;
                    break;
                case 'todaySupplies':
                    html = `
                        <div class="filter-option">
                            <label for="topTodayMilitary">今日武勋前N名</label>
                            <input type="number" id="topTodayMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomTodayMilitary">今日武勋后N名</label>
                            <input type="number" id="bottomTodayMilitary" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="topTodaySupplies">今日辎重使用前N名</label>
                            <input type="number" id="topTodaySupplies" min="1" value="10">
                        </div>
                        <div class="filter-option">
                            <label for="bottomTodaySupplies">今日辎重使用后N名</label>
                            <input type="number" id="bottomTodaySupplies" min="1" value="10">
                        </div>
                    `;
                    break;
            }
            
            filterOptions.innerHTML = html;
        }
        
        // 筛选数据
        function filterData() {
            if (!hasUploadedFiles) {
                alert('请先上传文件');
                return;
            }
            
            if (!currentData[currentDataType]) {
                alert(`请先上传${getDataTypeName(currentDataType)}文件`);
                return;
            }
            
            const data = currentData[currentDataType];
            currentFilterResults = {}; // 重置筛选结果
            
            switch(currentDataType) {
                case 'current':
                    const topWeekMilitary = parseInt(document.getElementById('topWeekMilitary').value);
                    const bottomWeekMilitary = parseInt(document.getElementById('bottomWeekMilitary').value);
                    const topProsperity = parseInt(document.getElementById('topProsperity').value);
                    const bottomProsperity = parseInt(document.getElementById('bottomProsperity').value);
                    
                    // 周武勋前N名
                    const sortedByWeekMilitary = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['周武勋']) || 0;
                        const bVal = parseFloat(b['周武勋']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['周武勋前' + topWeekMilitary + '名'] = sortedByWeekMilitary.slice(0, topWeekMilitary);
                    
                    // 周武勋后N名
                    currentFilterResults['周武勋后' + bottomWeekMilitary + '名'] = sortedByWeekMilitary.slice(-bottomWeekMilitary);
                    
                    // 繁荣度前N名
                    const sortedByProsperity = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['繁荣度']) || 0;
                        const bVal = parseFloat(b['繁荣度']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['繁荣度前' + topProsperity + '名'] = sortedByProsperity.slice(0, topProsperity);
                    
                    // 繁荣度后N名
                    currentFilterResults['繁荣度后' + bottomProsperity + '名'] = sortedByProsperity.slice(-bottomProsperity);
                    break;
                    
                case 'history':
                    const topHistoryMilitary = parseInt(document.getElementById('topHistoryMilitary').value);
                    const bottomHistoryMilitary = parseInt(document.getElementById('bottomHistoryMilitary').value);
                    const topProsperityHistory = parseInt(document.getElementById('topProsperity').value);
                    const bottomProsperityHistory = parseInt(document.getElementById('bottomProsperity').value);
                    
                    // 历史武勋前N名
                    const sortedByHistoryMilitary = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['武勋']) || 0;
                        const bVal = parseFloat(b['武勋']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['历史武勋前' + topHistoryMilitary + '名'] = sortedByHistoryMilitary.slice(0, topHistoryMilitary);
                    
                    // 历史武勋后N名
                    currentFilterResults['历史武勋后' + bottomHistoryMilitary + '名'] = sortedByHistoryMilitary.slice(-bottomHistoryMilitary);
                    
                    // 繁荣度前N名
                    const sortedByProsperityHistory = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['繁荣度']) || 0;
                        const bVal = parseFloat(b['繁荣度']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['繁荣度前' + topProsperityHistory + '名'] = sortedByProsperityHistory.slice(0, topProsperityHistory);
                    
                    // 繁荣度后N名
                    currentFilterResults['繁荣度后' + bottomProsperityHistory + '名'] = sortedByProsperityHistory.slice(-bottomProsperityHistory);
                    break;
                    
                case 'currentSupplies':
                    const topWeekMilitarySupplies = parseInt(document.getElementById('topWeekMilitary').value);
                    const bottomWeekMilitarySupplies = parseInt(document.getElementById('bottomWeekMilitary').value);
                    const topSupplies = parseInt(document.getElementById('topSupplies').value);
                    const bottomSupplies = parseInt(document.getElementById('bottomSupplies').value);
                    
                    // 本周武勋前N名
                    const sortedByWeekMilitarySupplies = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['周武勋']) || 0;
                        const bVal = parseFloat(b['周武勋']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['本周武勋前' + topWeekMilitarySupplies + '名'] = sortedByWeekMilitarySupplies.slice(0, topWeekMilitarySupplies);
                    
                    // 本周武勋后N名
                    currentFilterResults['本周武勋后' + bottomWeekMilitarySupplies + '名'] = sortedByWeekMilitarySupplies.slice(-bottomWeekMilitarySupplies);
                    
                    // 本周辎重使用前N名
                    const sortedBySupplies = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['本周消耗']) || 0;
                        const bVal = parseFloat(b['本周消耗']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['本周辎重使用前' + topSupplies + '名'] = sortedBySupplies.slice(0, topSupplies);
                    
                    // 本周辎重使用后N名
                    currentFilterResults['本周辎重使用后' + bottomSupplies + '名'] = sortedBySupplies.slice(-bottomSupplies);
                    break;
                    
                case 'todaySupplies':
                    const topTodayMilitary = parseInt(document.getElementById('topTodayMilitary').value);
                    const bottomTodayMilitary = parseInt(document.getElementById('bottomTodayMilitary').value);
                    const topTodaySupplies = parseInt(document.getElementById('topTodaySupplies').value);
                    const bottomTodaySupplies = parseInt(document.getElementById('bottomTodaySupplies').value);
                    
                    // 今日武勋前N名
                    const sortedByTodayMilitary = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['今日武勋']) || 0;
                        const bVal = parseFloat(b['今日武勋']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['今日武勋前' + topTodayMilitary + '名'] = sortedByTodayMilitary.slice(0, topTodayMilitary);
                    
                    // 今日武勋后N名
                    currentFilterResults['今日武勋后' + bottomTodayMilitary + '名'] = sortedByTodayMilitary.slice(-bottomTodayMilitary);
                    
                    // 今日辎重使用前N名
                    const sortedByTodaySupplies = [...data].sort((a, b) => {
                        const aVal = parseFloat(a['今日消耗']) || 0;
                        const bVal = parseFloat(b['今日消耗']) || 0;
                        return bVal - aVal;
                    });
                    currentFilterResults['今日辎重使用前' + topTodaySupplies + '名'] = sortedByTodaySupplies.slice(0, topTodaySupplies);
                    
                    // 今日辎重使用后N名
                    currentFilterResults['今日辎重使用后' + bottomTodaySupplies + '名'] = sortedByTodaySupplies.slice(-bottomTodaySupplies);
                    break;
            }
            
            displayResults(currentFilterResults);
        }
        
        // 获取数据类型名称
        function getDataTypeName(type) {
            const names = {
                'current': '本周基础数据',
                'history': '历史基础数据',
                'currentSupplies': '本周辎重使用数据',
                'todaySupplies': '今日辎重使用数据'
            };
            return names[type] || '数据';
        }
        
        // 显示结果
        function displayResults(results) {
            if (Object.keys(results).length === 0) {
                resultsContainer.innerHTML = '<div class="no-data">没有符合条件的数据</div>';
                return;
            }
            
            let html = '';
            
            for (const [category, data] of Object.entries(results)) {
                if (data.length === 0) continue;
                
                html += `<div class="result-category">`;
                html += `<h3>${category}</h3>`;
                
                // 获取所有可能的列名
                const allKeys = new Set();
                data.forEach(item => {
                    Object.keys(item).forEach(key => allKeys.add(key));
                });
                
                const headers = Array.from(allKeys);
                
                html += '<table><thead><tr>';
                headers.forEach(header => {
                    html += `<th>${header}</th>`;
                });
                html += '</tr></thead><tbody>';
                
                data.forEach(row => {
                    html += '<tr>';
                    headers.forEach(header => {
                        let value = row[header] || '';
                        
                        // 在显示时，如果数字大于10000，可以显示为"X万"格式
                        if (typeof value === 'number' && value >= 10000) {
                            value = (value / 10000).toFixed(1) + '万';
                        }
                        
                        html += `<td>${value}</td>`;
                    });
                    html += '</tr>';
                });
                
                html += '</tbody></table></div>';
            }
            
            if (html === '') {
                html = '<div class="no-data">没有符合条件的数据</div>';
            }
            
            resultsContainer.innerHTML = html;
        }
        
        // 导出筛选结果为Excel
        function exportFilterResults() {
            if (Object.keys(currentFilterResults).length === 0) {
                alert('请先进行数据筛选');
                return;
            }
            
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            
            // 为每个筛选结果创建工作表
            for (const [sheetName, data] of Object.entries(currentFilterResults)) {
                if (data.length === 0) continue;
                
                // 获取所有可能的列名
                const allKeys = new Set();
                data.forEach(item => {
                    Object.keys(item).forEach(key => allKeys.add(key));
                });
                
                const headers = Array.from(allKeys);
                const rows = data.map(item => {
                    return headers.map(header => {
                        let value = item[header] || '';
                        
                        // 在导出时，如果数字大于10000，可以显示为"X万"格式
                        if (typeof value === 'number' && value >= 10000) {
                            return (value / 10000).toFixed(1) + '万';
                        }
                        
                        return value;
                    });
                });
                
                const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
                
                // 限制sheet名称长度（Excel限制为31个字符）
                const safeSheetName = sheetName.length > 31 ? sheetName.substring(0, 31) : sheetName;
                XLSX.utils.book_append_sheet(wb, ws, safeSheetName);
            }
            
            // 生成文件名
            const fileName = `筛选结果_${getDataTypeName(currentDataType)}_${new Date().toISOString().slice(0, 10)}.xlsx`;
            
            // 导出文件
            XLSX.writeFile(wb, fileName);
        }
        
        // 导出到腾讯文档
        function exportToTencentDocs() {
            if (Object.keys(currentFilterResults).length === 0) {
                alert('请先进行数据筛选');
                return;
            }
            
            // 将数据转换为CSV格式
            let csvContent = '';
            
            for (const [sheetName, data] of Object.entries(currentFilterResults)) {
                if (data.length === 0) continue;
                
                // 添加sheet名称作为标题
                csvContent += `=== ${sheetName} ===\n`;
                
                // 获取所有可能的列名
                const allKeys = new Set();
                data.forEach(item => {
                    Object.keys(item).forEach(key => allKeys.add(key));
                });
                
                const headers = Array.from(allKeys);
                
                // 添加表头
                csvContent += headers.join(',') + '\n';
                
                // 添加数据行
                data.forEach(item => {
                    const row = headers.map(header => {
                        let value = item[header] || '';
                        
                        // 在导出时，如果数字大于10000，可以显示为"X万"格式
                        if (typeof value === 'number' && value >= 10000) {
                            return (value / 10000).toFixed(1) + '万';
                        }
                        
                        // 处理包含逗号的值
                        if (typeof value === 'string' && value.includes(',')) {
                            return `"${value}"`;
                        }
                        
                        return value;
                    });
                    csvContent += row.join(',') + '\n';
                });
                
                csvContent += '\n'; // 添加空行分隔不同的sheet
            }
            
            // 创建Blob对象
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            
            // 生成腾讯文档导入链接
            const tencentDocsUrl = `https://docs.qq.com/desktop/upload?url=${encodeURIComponent(url)}`;
            
            // 显示模态框
            tencentLink.textContent = tencentDocsUrl;
            tencentModal.style.display = 'flex';
        }
        
        // 复制腾讯文档链接
        function copyTencentLink() {
            const linkText = tencentLink.textContent;
            navigator.clipboard.writeText(linkText).then(() => {
                alert('链接已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制链接');
            });
        }
    </script>
</body>
</html>